package com.kmlitro.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.kmlitro.entity.Usuario;
import com.kmlitro.entity.dao.VeiculoDAO;

public class KmLitroImage extends HttpServlet{

	private static final long serialVersionUID = 3328624072869450481L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		String stringV =  (String) request.getSession().getAttribute("vehicleId");
		
		int vehId = Integer.parseInt(stringV);

		System.out.println("request: "+request);
		System.out.println("vehId: " + vehId);
		if (!isMultipart) {
			System.out.println("File Not Uploaded");
		} else {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = null;

			try {
				items = upload.parseRequest(request);
				System.out.println("items: "+items);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()){
					String name = item.getFieldName();
					System.out.println("name: "+name);
					String value = item.getString();
					System.out.println("value: "+value);
				} else {
					try {
						String itemName = item.getName();
						Random generator = new Random();
						int r = Math.abs(generator.nextInt());

						String reg = "[.*]";
						String replacingtext = "";
						System.out.println("Text before replacing is:-" + 
								itemName);
						Pattern pattern = Pattern.compile(reg);
						Matcher matcher = pattern.matcher(itemName);
						StringBuffer buffer = new StringBuffer();

						while (matcher.find()) {
							matcher.appendReplacement(buffer, replacingtext);
						}
						int IndexOf = itemName.indexOf("."); 
						String domainName = itemName.substring(IndexOf);
						System.out.println("domainName: "+domainName);

						String finalimage = buffer.toString()+"_"+r+domainName;
						System.out.println("Final Image==="+finalimage);

						try {
							File savedFile = new File("/usr/share/apache-tomcat-7.0.21/webapps/ROOT/images/carros/"+finalimage);
							item.write(savedFile);
						} catch (Exception e1) {
							e1.printStackTrace();
						}


						try {
							VeiculoDAO vDAO = new VeiculoDAO();

							vDAO.updateImage(vehId, "/images/carros/"+ finalimage);

							request.setAttribute("sucess", true);

							response.sendRedirect("/editaMeuVeiculo.jsp?vehId=" + vehId + "&sucess=true");


						} catch (Exception e) {
							System.out.println(e.getMessage());
						}  
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}